<?php

namespace Admin\Model\DAO;

use Zend\Db\TableGateway\AbstractTableGateway;
use Admin\Entity\Author;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Where;

class AuthorTable extends AbstractTableGateway {

    protected $table;
    protected $adapter;
    protected $resultSetPrototype;

    public function __construct($adapter) {
        $this->table = 'lib_bookauthors';
        $this->adapter = $adapter;
        $this->resultSetPrototype = new ResultSet();
    }

    public function saveAuthor(Author $author) {
        $data = $author->getArrayCopy();
        try {
            $this->insert($data);
            return true;
        } catch (Exception $e) {
            echo "loi insert book roi";
        }
        return false;
    }

    public function getAuhorFromBarcode($bookBarcode) {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from(array('ba' => $this->table));
        $where = new Where();
        $where->equalTo('ba.bookBarcode', $bookBarcode);
        $select->where($where);
        // you can check your query by echo-ing :
        //  echo $select->getSqlString();
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $resultSet = clone $this->resultSetPrototype;
        $resultSet->initialize($result);
        return $resultSet;
        if (!$resultSet)
            return null;
        return $resultSet;
    }

    public function getAuthorFormName($authorName) {
        $sql = new Sql($this->adapter);
        $select = $sql->select();
        $select->from(array('ba' => $this->table))
                ->join(array('bs' => 'lib_bookstores'), 'ba.bookBarcode = bs.bookBarcode');
        $where = new Where();
        $where->like('ba.author', '%' . $authorName . '%');
        $select->where($where);
        $statement = $sql->prepareStatementForSqlObject($select);
        $result = $statement->execute();
        $resultSet = clone $this->resultSetPrototype;
        $resultSet->initialize($result);
        $resultSet->buffer();
        $resultSet->next();
        return $resultSet;
    }

}

?>